//
//  WmcWatermarkView.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/5.
//

import UIKit
import YPBedrock

extension WmcWatermarkContentView {
    enum MarginsCalibration {
        case top, left, bottom, right
    }
}

// MARK: - [WmcWatermarkContentView]

class WmcWatermarkContentView: WmcBaseView {
    // Open

    /// 水印布局完成回调
    open var layoutWatermarksBlock: YPBlock.Empty?

    // Internal

    /// 水印视图
    var watermarkView: WmcBaseWatermarkTemplateView?

    /// 水印模型
    weak var watermarkModel: WmcWatermarkDetailModel?

    /// 水印视图开始布局的回调
    var watermarkLayoutBlock: YPBlock.OneParam<[UIView]>?

    /// 水印视图移动的回调
    var watermarkMoveBlock: YPBlock.OneParam<WmcBaseWatermarkTemplateView>?

    /// 水印视图点击的回调
    var watermarkActionBlock: YPBlock.OneParam<UIView>?

    /// 水印大边距校准
    var watermarkBigMarginsCalibration: [MarginsCalibration] = [.right, .bottom, .left, .top]

    /// 水印小边距校准
    var watermarkSmallMarginsCalibration: [MarginsCalibration] = [.right, .top, .left, .bottom]

    /// 可被触发的视图
    var hitsViews: [UIView] = []

    /// 正常点位
    var portraitPoint: CGPoint?

    /// 反向点位
    var portraitUpsideDownPoint: CGPoint?

    /// 左侧点位
    var landscapeLeftPoint: CGPoint?

    /// 右侧点位
    var landscapeRightPoint: CGPoint?

    /// 拖动边距
    var panEdges: UIEdgeInsets = .YP.Create(2)

    /// 全屏水印
    var fullScreenViews: [UIView] = []

    /// 锁定正向
    var isLockPortrait: Bool = false

    /// 官方水印
    lazy var officialWatermarkImageView: UIImageView = {
        let imageView = UIImageView(image: "home_official_watermark".wmc_image)
        imageView.contentMode = .scaleAspectFit
        imageView.isHidden = true
        setShadow(imageView)
        return imageView
    }()

    lazy var brandContentView: WmcBrandContentView = {
        let view = WmcBrandContentView()
        view.brandHitBrandCallBlock = { [weak self] in
            guard let weakSelf = self,
                  weakSelf.watermarkModel?.optionBrand()?.brand.locationType == .followWatermark else { return nil }
            return weakSelf.watermarkView
        }
        return view
    }()

    /// 是否一直锁定反转大小来约束范围，默认反转
    var isLockReverse: Bool = true

    /// 是否允许水印拖动
    var isWatermarkMoveBlock: YPBlock.Return<Bool> = { return true }

    /// 渲染样式
    var styleMode: WmcBaseWatermarkTemplateView.StyleMode = .dynamicDraw

    /// 是否使用认证视图
    var showCertification: Bool = true

    /// 二级仿射变换
    var secondaryTransform: CGAffineTransform? {
        didSet { updateWatermark() }
    }

    override func config() {
        backgroundColor = .clear
    }

    override func makeUI() {
        addSubview(officialWatermarkImageView)
        officialWatermarkImageView.snp.makeConstraints { make in
            make.right.bottom.equalToSuperview()
            make.size.equalTo(CGSize(width: 60, height: 60))
        }

        addSubview(brandContentView)
        brandContentView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }

    /// 更新水印
    func updateWatermark() {
        guard let watermarkModel = watermarkModel else { return }
        setWatermarkModel(watermarkModel, styleMode: styleMode, showCertification: showCertification)
    }

    /// 更新水印
    func reloadWatermark(styleMode: WmcBaseWatermarkTemplateView.StyleMode = .dynamicDraw,
                         showCertification: Bool = true)
    {
        guard let watermarkModel = watermarkModel else { return }
        watermarkView?.removeFromSuperview()
        watermarkView = nil
        setWatermarkModel(watermarkModel, styleMode: styleMode, showCertification: showCertification)
    }

    /// 设置水印
    func setWatermarkModel(_ watermarkModel: WmcWatermarkDetailModel,
                           styleMode: WmcBaseWatermarkTemplateView.StyleMode = .dynamicDraw,
                           showCertification: Bool = true)
    {
        DispatchQueue.main.async { [weak self] in
            guard let self = self else { return }
            self.watermarkModel = watermarkModel
            self.styleMode = styleMode

            let isLoad = (self.watermarkView?.watermarkModel?.templateId != watermarkModel.templateId) ||
                (self.showCertification != showCertification)
            if isLoad { // 模版变化，重新创建
                self.watermarkView?.removeFromSuperview()
                self.watermarkView = nil

                guard let templateView = watermarkModel.createTemplateView(styleMode: styleMode,
                                                                           showCertification: showCertification) else { return }
                self.watermarkView = templateView
                self.showCertification = showCertification
            }
            guard let templateView = self.watermarkView else { return }
            // 清空边距
            templateView.edgeCompensateDistance = .zero
            // 配置品牌内容视图
            self.brandContentView.watermarkView = templateView
            self.brandContentView.removeBrand()
            // 接收品牌图配置回调
            templateView.configOptionBrandBlock = { [weak self] optionBrand in
                guard let weakSelf = self else { return }
                weakSelf.brandContentView.configBrand(optionBrand)
            }
            // 移除品牌图回调
            templateView.removeBrandBlock = { [weak self] in
                guard let weakSelf = self else { return }
                weakSelf.brandContentView.removeBrand()
            }
            // 配置和渲染
            templateView.configWatermarkModel(watermarkModel, styleMode: styleMode)
            // 添加水印视图
            self.addSubview(templateView)
            // 设置水印视图的各项属性
            self.setttingWatermarkView()

            // 设置二级缩放 主要用于水印二次编辑
            if let secondaryTransform = self.secondaryTransform {
                templateView.transform = templateView.transform.concatenating(secondaryTransform)
                self.brandContentView.secondaryTransform = secondaryTransform
            }
        }
    }

    func setttingWatermarkView() {
        guard let watermarkView = watermarkView else { return }
        // 添加和约束
        watermarkView.snp.makeConstraints { make in
            make.left.equalTo(panEdges.left)
            make.bottom.equalTo(-panEdges.bottom)
            if let defaultWidth = watermarkView.defaultWidth {
                make.width.equalTo(defaultWidth)
            }
        }

        // 拖动手势
        let pan = UIPanGestureRecognizer.YP.Create { [weak self] pan in
            guard let weakSelf = self else { return }
            guard let watermarkView = weakSelf.watermarkView else { return }
            weakSelf.moveWatermarkView(pan)
            // 回调
            weakSelf.watermarkMoveBlock?(watermarkView)
        }
        watermarkView.addGestureRecognizer(pan)

        // 点击手势
        let tap = UITapGestureRecognizer.YP.Create { [weak self] _ in
            guard let weakSelf = self else { return }
            guard let watermarkView = weakSelf.watermarkView else { return }
            weakSelf.watermarkActionBlock?(watermarkView)
        }
        watermarkView.addGestureRecognizer(tap)

        // 移除全屏水印
        fullScreenViews.forEach { view in
            view.removeFromSuperview()
        }
        // 设置全屏水印
        fullScreenViews = watermarkView.createFullScreenViews()
        fullScreenViews.forEach { [weak self] view in
            guard let weakSelf = self else { return }
            weakSelf.insertSubview(view, belowSubview: watermarkView)
            watermarkView.makeFullScreenViews(makeView: view, superView: weakSelf) // 调用布局
        }
    }

    /// 移动水印
    func moveWatermarkView(_ pan: UIPanGestureRecognizer) {
        guard isWatermarkMoveBlock() else { return }
        guard let watermarkView = watermarkView,
              watermarkView.frame.size != .zero,
              let panView = pan.view else { return }
        let translation = pan.translation(in: watermarkView)
        let center = CGPoint(x: panView.center.x + translation.x,
                             y: panView.center.y + translation.y)
        moveWatermarkView(center)
        pan.setTranslation(CGPoint.zero, in: watermarkView) // 归零
    }

    /// 移动水印
    func moveWatermarkView(_ center: CGPoint) {
        guard let watermarkView = watermarkView,
              watermarkView.frame.size != .zero else { return }

        let halfHeight = watermarkView.frame.height / 2
        let halfWidth = watermarkView.frame.width / 2
        // 判断边距
        var centerY = center.y
        var centerX = center.x
        // 与横竖屏有关
        var selfHeight = frame.size.height
        var selfWidth = frame.size.width
        if isLockReverse { // 锁定反转
            switch WmcMotionManager.shared.orientation.value {
            case .landscapeRight,
                 .landscapeLeft:
                selfHeight = frame.size.width
                selfWidth = frame.size.height
            default: break
            }
        }
        // 边界补偿
        let edgeCompensateDistance = watermarkView.edgeCompensateDistance
        // 开始计算 有运算顺序要求
        let bottom = centerY + halfHeight + edgeCompensateDistance.bottom
        if bottom > (selfHeight - panEdges.bottom) { // 底部
            centerY = selfHeight - (panEdges.bottom + halfHeight + edgeCompensateDistance.bottom)
        }

        let top = centerY - (halfHeight + edgeCompensateDistance.top)
        if top < panEdges.top { // 顶部
            centerY = panEdges.top + halfHeight + edgeCompensateDistance.top
        }

        let right = centerX + halfWidth + edgeCompensateDistance.right
        if right > (selfWidth - panEdges.right) { // 右侧
            centerX = selfWidth - (panEdges.right + halfWidth + edgeCompensateDistance.right)
        }

        let left = centerX - (halfWidth + edgeCompensateDistance.left)
        if left < panEdges.left { // 左侧
            centerX = panEdges.left + halfWidth + edgeCompensateDistance.left
        }

        watermarkView.center = CGPoint(x: centerX, y: centerY)
        // 记录点位
        switch WmcMotionManager.shared.orientation.value {
        case .portrait: portraitPoint = watermarkView.center
        case .landscapeLeft: landscapeLeftPoint = watermarkView.center
        case .portraitUpsideDown: portraitUpsideDownPoint = watermarkView.center
        case .landscapeRight: landscapeRightPoint = watermarkView.center
        default: break
        }

        // 通知品牌内容视图
        brandContentView.updateBrandViewFrame()
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        guard let watermarkView = watermarkView else { return }

        if isLockPortrait {
            if let portraitPoint = portraitPoint {
                watermarkView.center = portraitPoint
            }
        } else {
            // 显示上一次拖动的坐标
            switch WmcMotionManager.shared.orientation.value {
            case .portrait:
                if let portraitPoint = portraitPoint {
                    watermarkView.center = portraitPoint
                }
            case .landscapeLeft:
                if let landscapeLeftPoint = landscapeLeftPoint {
                    watermarkView.center = landscapeLeftPoint
                }
            case .portraitUpsideDown:
                if let portraitUpsideDownPoint = portraitUpsideDownPoint {
                    watermarkView.center = portraitUpsideDownPoint
                }
            case .landscapeRight:
                if let landscapeRightPoint = landscapeRightPoint {
                    watermarkView.center = landscapeRightPoint
                }
            default: break
            }
        }

        // 预览区域高度大小与纵横平有关
        var previewHeight = frame.size.height
        var previewWidth = frame.size.width
        if isLockReverse { // 是否反转
            if isLockPortrait { // 锁正向
                
            }else{
                switch WmcMotionManager.shared.orientation.value {
                case .landscapeLeft,
                     .landscapeRight:
                    previewHeight = frame.size.width
                    previewWidth = frame.size.height
                default: break
                }
            }
        }

        // 校准水印位置，防止出界
        // 校准顶部
        func calibrationTop() {
            let topRect = panEdges.top + watermarkHalfSize.height + edgeCompensateDistance.top
            if watermarkView.center.y < topRect {
                watermarkView.center = CGPoint(x: watermarkView.center.x, y: topRect)
            }
        }

        // 校准左侧
        func calibrationLeft() {
            let leftRect = panEdges.left + watermarkHalfSize.width + edgeCompensateDistance.left
            if watermarkView.center.x < leftRect {
                watermarkView.center = CGPoint(x: leftRect, y: watermarkView.center.y)
            }
        }

        // 校准底部
        func calibrationBottom() {
            let bottomRect = previewHeight - (panEdges.bottom + watermarkHalfSize.height + edgeCompensateDistance.bottom)
            if watermarkView.center.y > bottomRect {
                watermarkView.center = CGPoint(x: watermarkView.center.x, y: bottomRect)
            }
        }

        // 校准右侧
        func calibrationRight() {
            let rightRect = previewWidth - (panEdges.right + watermarkHalfSize.width + edgeCompensateDistance.right)
            if watermarkView.center.x > rightRect {
                watermarkView.center = CGPoint(x: rightRect, y: watermarkView.center.y)
            }
        }

        let watermarkSize = CGSize(width: watermarkView.frame.width,
                                   height: watermarkView.frame.height)
        let watermarkHalfSize = CGSize(width: watermarkSize.width / 2, height: watermarkSize.height / 2)
        // 边界补偿
        let edgeCompensateDistance = watermarkView.edgeCompensateDistance

        if watermarkSize.height + watermarkView.edgeCompensateDistance.yp.vertical > previewHeight { // 水印比预览地方大
            // 进行校准，有运算顺序要求
            for cas in watermarkBigMarginsCalibration {
                switch cas {
                case .top: calibrationTop()
                case .left: calibrationLeft()
                case .bottom: calibrationBottom()
                case .right: calibrationRight()
                }
            }
        } else { // 水印比预览小
            //  有运算顺序要求
            for cas in watermarkSmallMarginsCalibration {
                switch cas {
                case .top: calibrationTop()
                case .left: calibrationLeft()
                case .bottom: calibrationBottom()
                case .right: calibrationRight()
                }
            }
        }

        // 需要触碰的水印进行回调
        // 使控制视图点击事件何其不冲突
        // 水印视图
        hitsViews.removeAll()
        hitsViews.append(watermarkView)
        if let brandView = brandContentView.brandView {
            hitsViews.append(brandView)
        }
        watermarkLayoutBlock?(hitsViews)

        // 通知品牌内容视图
        brandContentView.updateBrandViewFrame()
        layoutWatermarksBlock?()
    }

    /// 设置视图阴影
    func setShadow(_ view: UIView, color: UIColor = UIColor.wmc_grayH5_606066) {
        view.layer.shadowColor = color.cgColor
        view.layer.shadowRadius = 4
        view.layer.shadowOffset = CGSize(width: 0, height: 1)
        view.layer.shadowOpacity = 0.8
    }

    /// 显示官方水印
    func showOfficialWatermark() {
        officialWatermarkImageView.isHidden = false
    }

    /// 隐藏官方水印
    func hideOfficialWatermark() {
        officialWatermarkImageView.isHidden = true
    }
}
